package com.example.membersteward.controller;

import com.example.membersteward.common.CommonResult;
import com.example.membersteward.entity.User;
import com.example.membersteward.entity.vo.UserVo;
import com.example.membersteward.service.RoleUserService;
import com.example.membersteward.service.UserService;
import com.example.membersteward.util.BaseUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

@RestController
public class UserController {
    @Resource
    UserService userService;

    @Resource
    ObjectMapper objectMapper;

    @Resource
    RoleUserService roleUserService;

    @PostMapping("/auth/login")
    public CommonResult login(@RequestBody User user) {
        return userService.login(user);
    }

    @PostMapping("/auth/register")
    public CommonResult register(@RequestBody UserVo user) {
        return userService.register(user);
    }

    @PostMapping("/api/getUserByPage")
    public CommonResult getUserByPage(@RequestParam(defaultValue = "1") int pageNum,
                                      @RequestParam(defaultValue = "10") int pageSize,
                                      @RequestBody UserVo user) {
        return userService.getUserByPage(pageNum,pageSize,user);
    }

    @PostMapping("/api/resetPassword")
    public CommonResult resetPassword(@RequestBody User user) {
        return userService.resetPassword(user);
    }

    @GetMapping("/api/deleteUser")
    public CommonResult deleteUser(String userIds) {
        CommonResult commonResult = roleUserService.isAdmin();
        if (commonResult.isError()) {
            return commonResult;
        }
        return userService.deleteUser(userIds);
    }

    @PostMapping("/api/updateUser")
    public CommonResult updateUser(@RequestParam(required = false) MultipartFile file, @RequestParam("user") String userJson) {
        try {
            UserVo user = objectMapper.readValue(userJson, UserVo.class);
            if (BaseUtils.isNull(file)) {
                user.setImgPath(null);
            }
            return userService.updateUser(file, user);
        } catch (Exception e) {
            // 处理异常
            return CommonResult.error("解析用户信息失败");
        }
    }
}
